import { Body, Controller, Del, Inject, Post } from '@midwayjs/core'
import { Context } from '@midwayjs/koa'
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags
} from '@midwayjs/swagger'
import { Validate } from '@midwayjs/validate'
import { ExcelService } from '@ttou/midway-excel'

import { Permission } from '@/decorator'
import { DeleteDTO } from '@/dto'

import { FindLoginLogPageDTO } from './login-log.dto'
import { LoginLogExportSerialize } from './login-log.serialize'
import { LoginLogService } from './login-log.service'
import { GetLoginLogPageVO } from './login-log.vo'

@ApiBearerAuth()
@ApiTags('监控/登录日志接口')
@Controller('/monitor/loginLog')
export class LoginLogController {
  @Inject()
  ctx: Context

  @Inject()
  loginLogService: LoginLogService

  @Inject()
  excelService: ExcelService

  @ApiOperation({ summary: '获取登录日志分页' })
  @ApiResponse({ status: 200, type: GetLoginLogPageVO })
  @Permission('monitor:loginlog:list')
  @Post('/page')
  @Validate()
  async getLoginLogPage(@Body() dto: FindLoginLogPageDTO) {
    return await this.loginLogService.handleFindPage(dto)
  }

  @ApiOperation({ summary: '导出登录日志分页' })
  @Permission('monitor:loginlog:export')
  @Post('/export')
  @Validate()
  async exportLoginLogPage(@Body() dto: FindLoginLogPageDTO) {
    const { list } = await this.loginLogService.handleFindPage(dto)

    const result = await this.excelService.handleExport({
      sheetName: '登录日志',
      filename: '登录日志报表',
      Cls: LoginLogExportSerialize,
      data: list
    })

    this.ctx.set(result.headers)
    this.ctx.body = result.body
  }

  @ApiOperation({ summary: '删除登录日志' })
  @Permission('monitor:loginlog:remove')
  @Del('/delete')
  @Validate()
  async deleteLoginLog(@Body() dto: DeleteDTO) {
    await this.loginLogService.handleDelete(dto)
  }

  @ApiOperation({ summary: '清空登录日志' })
  @Permission('monitor:loginlog:remove')
  @Del('/clear')
  async clearLoginLog() {
    await this.loginLogService.handleClear()
  }
}
